package cardwall.client.view;

import org.puremvc.java.multicore.patterns.mediator.Mediator;
import org.puremvc.java.multicore.interfaces.INotification;
import cardwall.client.view.WallPanel;
import cardwall.client.ApplicationFacade;
import cardwall.client.model.TasksProxy;
import cardwall.shared.Task;

import java.util.List;

/**
 * @author $LastChangedBy: vogensen $
 * @version $Revision: 2 $
 */
public class WallPanelMediator extends Mediator {

    public WallPanelMediator(WallPanel wallPanel) {
        super("WallPanelMediator", wallPanel);
        getWallPanel().init();
        getWallPanel().addCardUpdateListener(new CardUpdateListener() {
            public void onUpdate(CardPanel cardPanel) {
                Task task = cardPanel.getTask();
                task.setLeft((int)(getWallPanel().getWidgetLeft(cardPanel) / (getWallPanel().getOffsetWidth() / 1000.0)));
                task.setTop((int)(getWallPanel().getWidgetTop(cardPanel) / (getWallPanel().getOffsetHeight() / 1000.0)));
                TasksProxy tasksProxy = (TasksProxy) ApplicationFacade.getInstance().retrieveProxy(TasksProxy.PROXYNAME);
                tasksProxy.updateTask(task);
            }
        });
        getWallPanel().addCardSelectedListener(new CardSelectedListener() {
            public void onSelection(CardPanel cardPanel) {
                sendNotification(ApplicationFacade.SELECTION_CHANGED, cardPanel.getTask(), ApplicationFacade.NOTIFICATIONTYPE_DEFAULT);
            }
        });
    }

    private WallPanel getWallPanel() {
        return (WallPanel) viewComponent;
    }

    public String[] listNotificationInterests() {
        return new String[] {ApplicationFacade.TASKS_CHANGED, ApplicationFacade.WINDOW_RESIZED, ApplicationFacade.SELECTION_CHANGED};
    }

    public void handleNotification(INotification inotification) {
        if(inotification.getName().equals(ApplicationFacade.TASKS_CHANGED)) {
            getWallPanel().refreshTasks((List<Task>)inotification.getBody());

        } else if(inotification.getName().equals(ApplicationFacade.WINDOW_RESIZED)) {
            getWallPanel().repositionTasks();

        } else if(inotification.getName().equals(ApplicationFacade.SELECTION_CHANGED)) {
            getWallPanel().setSelected((Task)inotification.getBody());
        }
    }
}
